package edu.chinasoft.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.PrintWriter;
import javax.servlet.annotation.WebServlet;
import org.apache.log4j.Logger;

import edu.chinasoft.exception.UserNoExistsException;
import edu.chinasoft.pojo.User;
import edu.chinasoft.service.UserService;
import edu.chinasoft.service.UserServiceImp;

/**
 * 
 * @author cjogng
 * @date 2020年1月17日:下午2:53:10
 * @version V1.0
 * @Description: 用户登录功能
*/
@WebServlet(name="myLoginUserForServlet",value="/servlet/loginuserforservlet")
public class  LoginUserForServlet  extends HttpServlet {
	private static Logger logger = Logger.getLogger( LoginUserForServlet .class);
	private UserService userService = new UserServiceImp();
	/**
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		logger.debug(" LoginUserForServlet >doGet start.......");
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		//获取表单提交的数据
		String userName = request.getParameter("user_name");
		String userPassword = request.getParameter("user_password");
		String verificationCodeClient = request.getParameter("user_code_verification");
		
		HttpSession session = request.getSession(false);
		String verificationCodeServer = (String)session.getAttribute("verificationcodeserver");
		
		if(verificationCodeClient!=null&&verificationCodeServer!=null&&verificationCodeClient.equals(verificationCodeServer)) {
			//调用服务层方法查看该用户是否存在
			User user = new User(userName,userPassword);
			
			try {
				User userLogin = userService.loginUser(user);
				
				
				//创建Sesson对象
				session = request.getSession();
				session.setAttribute("user", userLogin);
							
				
				//没有任何异常，跳到显示表格页面
				response.sendRedirect(""+request.getContextPath()+"/main.html");

				
			} catch (UserNoExistsException e) {
				//有异常，表示登录失败
				response.sendRedirect(""+request.getContextPath()+"/login_fail.html");
			}
		}else {
			response.sendRedirect(""+request.getContextPath()+"/login.html");
		}
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		logger.debug(" LoginUserForServlet >doGet end.......");
	}
	
	/**
	 * 
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		logger.debug(" LoginUserForServlet >doPost start.......");
		this.doGet(request, response);
		
		logger.debug(" LoginUserForServlet >doPost end.......");
	}
	
}